// index.js
import { getStudentInfo, getMyCourseList } from '../../utils/api-v2';

Page({
  data: {
    userInfo: {
      name: '',
      number: '',
      className: '',
      majorName: '',
      avatarUrl: ''
    },
    stats: {
      selectedCount: 0,
      creditCount: 0,
      avgScore: 0
    }
  },

  onLoad() {
    // 页面加载时获取用户信息
    this.getUserInfo();
    this.getStats();
  },

  onShow() {
    // 页面显示时刷新统计数据
    this.getStats();
  },

  // 获取用户信息
  getUserInfo() {
    // 先尝试从本地存储读取
    const cachedUserInfo = wx.getStorageSync('userInfo');
    if (cachedUserInfo && cachedUserInfo.name) {
      this.setData({
        userInfo: cachedUserInfo
      });
    }

    // 调用接口获取最新信息
    getStudentInfo()
      .then((res) => {
        const userInfo = res.data || {};
        this.setData({
          userInfo: {
            name: userInfo.name || '未设置',
            number: userInfo.number || '',
            className: userInfo.className || '',
            majorName: userInfo.majorName || '',
            avatarUrl: '/images/ziliao.png'
          }
        });
        // 缓存到本地
        wx.setStorageSync('userInfo', this.data.userInfo);
      })
      .catch((err) => {
        console.error('获取用户信息失败:', err);
        // 使用缓存数据或默认数据
        if (!cachedUserInfo) {
          this.setData({
            userInfo: {
              name: '未登录',
              number: '',
              className: '',
              majorName: '',
              avatarUrl: '/images/ziliao.png'
            }
          });
        }
      });
  },

  // 获取统计数据
  getStats() {
    // 先从本地存储读取快速显示
    const myCourses = wx.getStorageSync('myCourses') || [];
    if (myCourses.length > 0) {
      this.calculateStats(myCourses);
    }

    // 调用接口获取最新数据
    getMyCourseList()
      .then((res) => {
        let courseList = res.data || [];
        
        // 统一字段名
        courseList = courseList.map(item => {
          const validId = item.studentCourseId || item.courseId || item.cid || item.course_id;
          return {
            ...item,
            id: validId
          };
        });
        
        // 缓存数据
        wx.setStorageSync('myCourses', courseList);
        
        // 计算统计
        this.calculateStats(courseList);
      })
      .catch((err) => {
        console.error('获取课程统计失败:', err);
      });
  },

  // 计算统计数据
  calculateStats(courseList) {
    const selectedCount = courseList.length;
    const creditCount = courseList.reduce((sum, item) => sum + (item.credit || 0), 0);
    
    // 计算平均分（只计算已有成绩的课程）
    const coursesWithScore = courseList.filter(item => item.score && item.score > 0);
    const avgScore = coursesWithScore.length > 0
      ? (coursesWithScore.reduce((sum, item) => sum + item.score, 0) / coursesWithScore.length).toFixed(1)
      : 0;
    
    this.setData({
      stats: {
        selectedCount,
        creditCount,
        avgScore
      }
    });
  },

  // 导航到选修课程页面
  navigateToSelectCourse() {
    wx.navigateTo({
      url: '/pages/select-course/select-course'
    });
  },

  // 导航到我的课程页面
  navigateToMyCourse() {
    wx.navigateTo({
      url: '/pages/my-course/my-course'
    });
  },

  // 导航到课表查询页面
  navigateToTimetable() {
    wx.navigateTo({
      url: '/pages/timetable/timetable'
    });
  }
});
